#pragma once
#include "Log.hpp"
#include "uncopyable.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

// UDP_echo_Server 的服务端：接受并显示客户端发送的信息，最终把信息发回客户端
using namespace log_ddsm;

enum CON
{
    default_sockfd = -1,
    default_localport = -1,
    socket_err = 1,
    bind_err = 3
};

class UdpServer : public uncopyable // 服务器一般无法拷贝，赋值
{
public:
    UdpServer(const std::string& localip,uint16_t localport = default_localport)
        : _sockfd(default_sockfd)
        , _localport(localport)
        , _localip(localip)
        , _isrunning(false)
    {
    }
    void Init()
    {
        // 创建一个udp的网络套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket creat fail!\n");
            exit(socket_err);
        }
        LOG(DEBUG, "socket creat success | socket = %d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));

        local.sin_family = AF_INET; 
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = inet_addr(_localip.c_str());

        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(FATAL,"bind fail!\n");
            exit(bind_err);
        }
        LOG(DEBUG,"socket bind success\n");

        // recvfrom();
    }
    void Start()
    {
        _isrunning = true;
        while(1)
        {
            //do service
        }
    }
    ~UdpServer()
    {
    }

private:
    int _sockfd;//网络套接字，类似于一个文件fd
    uint16_t _localport;//本进程的端口号
    std::string _localip;//本地的ip
    bool _isrunning;//服务器是否正在运行
};